import { login, getUserInfo, logout } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { commonLight } from 'naive-ui'
import router from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    roles: [],
    permissions: []
  }
}
const state = getDefaultState()

const mutations = {
  SET_TOKEN: (state, token: {}) => {
    state.token = token
  },
  SET_USER: (state, user: {}) => {
    state.userInfo = user
  },
  SET_ROLES: (state, roles: []) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions: []) => {
    state.permissions = permissions
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState)
  }
  
}

const actions = {
  /**
   * 登录
   * @param param0 
   * @param userInfo 
   * @returns 
   */
  async Login({ state, commit, rootState }, userInfo) {
    const username = userInfo.username.trim()
    const password = userInfo.password

    try {
      const response = await login(username, password)
      const { code, data } = response

      commit('SET_TOKEN', data.token)
      setToken(data.token)

      return Promise.resolve(response)
      
    } catch (error) {
      return Promise.reject(error)
    }
  },
  
  /**
   * 获取用户信息
   * @returns 
   */
  async GetUserInfo({ commit }) {
    try {
      const response = await getUserInfo()
      
      if (response.data) {
        const { user, roles, permissions } = response.data
        commit('SET_USER', user)
        commit('SET_ROLES', roles)
        commit('SET_PERMISSIONS', permissions)
      }

      return Promise.resolve(response)
    } catch (error) {
      return Promise.reject(error)
    }
  },
  
  async Logout({ commit }) {
    try {
      logout()
      removeToken()
      commit('SET_TOKEN', '')
      commit('RESET_STATE')
      resetRouter()
    } catch(error) {
      return Promise.reject(error)
    }
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
